#include "mprpcchannel.h"
#include <string>
#include "user.pb.h"
#include "mprpcapplication.h"
#include "rpcheader.pb.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "zookeeperutil.h"

void MprpcChannel::CallMethod(const google::protobuf::MethodDescriptor *method,
                              google::protobuf::RpcController *controller, const google::protobuf::Message *request,
                              google::protobuf::Message *response, google::protobuf::Closure *done)
{
    //请求格式 :         headr_size(4Byte) header_str(headr_size Byte) args_str
    //其中header_str:     service_name method_name args_size

    const google::protobuf::ServiceDescriptor *serviceDesc = method->service();
    std::string service_name = serviceDesc->name();
    std::string method_name = method->name();

    uint32_t args_size = 0;
    std::string args_str;
    if (request->SerializeToString(&args_str))
    {
        args_size = args_str.size();
    }
    else
    {
        controller->SetFailed("serializeTostring args_str error");
        return;
    }

    rpchaeder::RpcHaeder rpcHeader;
    rpcHeader.set_method_name(method_name);
    rpcHeader.set_service_name(service_name);
    rpcHeader.set_args_size(args_size);

    std::string header_str;
    uint32_t header_size;
    if (rpcHeader.SerializeToString(&header_str))
    {
        header_size = header_str.size();
    }
    else
    {
        controller->SetFailed("rpcHeader serialize error");
        return;
    }

    std::string msg_str;

    // msg_str.insert(0, std::string((char *)&header_size), 4);
    msg_str.insert(0, std::string((char *)&header_size, 4));

    msg_str += header_str;
    msg_str += args_str;

    //调试信息
    std::cout << "======================================" << std::endl;
    std::cout << "header_size : " << header_size << std::endl;
    std::cout << "RpcHeader_str : " << header_str << std::endl;
    std::cout << "service_name : " << service_name << std::endl;
    std::cout << "method_name : " << method_name << std::endl;
    std::cout << "args_size : " << args_size << std::endl;
    std::cout << "======================================" << std::endl;

    int clientfd = socket(AF_INET, SOCK_STREAM, 0);
    if (clientfd == -1)
    {
        controller->SetFailed("socket error");
        close(clientfd);
        return;
    }

    // std::string ip = MprpcApplication::getInstance().getConfig().load("rpcserverip");
    // uint16_t port = atoi(MprpcApplication::getInstance().getConfig().load("rpcserverport").c_str());

    // 改用zookeeper获取服务的ip地址和端口号
    ZkClient zkCli;
    zkCli.start();
    std::string path = "/" + service_name + "/" + method_name;
    std::string host_data = zkCli.getData(path.c_str());
    if (host_data == "")
    {
        controller->SetFailed(path + "is not exist!");
        return;
    }

    std::size_t idx = host_data.find(':');
    if (idx == std::string::npos)
    {
        controller->SetFailed(path + "address is invalid!");
        return;
    }
    std::string ip = host_data.substr(0, idx);
    uint16_t port = atoi(host_data.substr(idx + 1, host_data.size() - idx).c_str());

    sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = inet_addr(ip.c_str());
    addr.sin_port = htons(port);

    int ret = connect(clientfd, (sockaddr *)&addr, sizeof(addr));
    if (ret == -1)
    {
        controller->SetFailed("connect error");
        close(clientfd);
        return;
    }

    ret = write(clientfd, msg_str.c_str(), msg_str.size());
    if (ret == -1)
    {
        controller->SetFailed("write error");
        close(clientfd);
        return;
    }

    char res[1024] = {0};
    ret = read(clientfd, res, 1024);
    if (ret == -1)
    {
        controller->SetFailed("read error");
        close(clientfd);
        return;
    }

    // std::string res_str(res, 0, ret);
    // if (!response->ParseFromString(res_str))
    if (!response->ParseFromArray(res, ret))
    {
        controller->SetFailed("pares error");
        close(clientfd);
        return;
    }
    close(clientfd);
    return;
}